Skip to content

[net11.0] Add platform-neutral handler contracts for external platform backends - #37855

Merged
kubaflo merged 10 commits into
net11.0from
redth-external-handler-interface-contracts
Aug 29, 2026
Merged

kubaflo merged 10 commits into
net11.0from
redth-external-handler-interface-contracts

Conversation

@Redth

@Redth Redth commented Aug 26, 2026

Copy link
Copy Markdown
Member

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description of Change

Adds a small, additive set of platform-neutral handler contracts so that a platform backend shipping outside dotnet/maui can participate in .NET MAUI's strongly typed handler APIs using its own native view types.

The problem

Every per-control handler interface in Microsoft.Maui.Core declares PlatformView through a using PlatformView = ... alias that resolves to a different native type per target framework:

#if __IOS__ || MACCATALYST
using PlatformView = Microsoft.Maui.Platform.MauiLabel;
#elif MONOANDROID
using PlatformView = AndroidX.AppCompat.Widget.AppCompatTextView;
#elif WINDOWS
using PlatformView = Microsoft.UI.Xaml.Controls.TextBlock;
#elif TIZEN
using PlatformView = Tizen.UIExtensions.NUI.Label;
#elif (NETSTANDARD || !PLATFORM) || ...
using PlatformView = System.Object;
#endif

public partial interface ILabelHandler : IViewHandler
{
    new ILabel VirtualView { get; }
    new PlatformView PlatformView { get; }
}

The alias is baked into the compiled contract, so the interface can only be implemented by a handler whose native type is exactly the type MAUI picked. An external backend owns its own native types, so it cannot implement them:

TFM the backend consumes Compiled PlatformView Error
A platform TFM MAUI ships MAUI's own native type CS0738
The neutral net11.0 TFM non-nullable System.Object CS9333, plus CS8766 (error under TreatWarningsAsErrors)

Reproduced against the shipped Microsoft.Maui.Core 11.0.0-preview.7.26406.9 package with a plain net11.0 class library:

public class MyNativeLabel { }

public class MyLabelHandler : ViewHandler<ILabel, MyNativeLabel>, ILabelHandler
{
    public MyLabelHandler() : base(LabelHandler.Mapper) { }
    protected override MyNativeLabel CreatePlatformView() => new();
    ILabel ILabelHandler.VirtualView => VirtualView;
    MyNativeLabel ILabelHandler.PlatformView => PlatformView;   // CS9333
}
error CS9333: 'MyLabelHandler.PlatformView': type must be 'object' to match implemented member 'ILabelHandler.PlatformView'
error CS8766: Nullability of reference types in return type of 'object? ViewHandler.PlatformView.get' doesn't match
              implicitly implemented member 'object ILabelHandler.PlatformView.get'

46 handler interfaces in Core use the alias pattern. ILabelHandler, IContentViewHandler, ILayoutHandler and IWindowHandler are the ones a minimal backend hits first, because they are needed for the application → window → page → content → layout → label vertical slice. ILayoutHandler is the most damaging, because it is the only one of the four that carries real behavior (Add/Remove/Clear/Insert/Update/UpdateZIndex) rather than just typed accessors.

The solution

Three new interfaces. Nothing was moved, renamed or removed.

namespace Microsoft.Maui;

public interface IElementHandler<out TVirtualView, out TPlatformView> : IElementHandler
    where TVirtualView : IElement
    where TPlatformView : class
{
    new TVirtualView VirtualView { get; }
    new TPlatformView PlatformView { get; }
}

public interface IViewHandler<out TVirtualView, out TPlatformView>
    : IElementHandler<TVirtualView, TPlatformView>, IViewHandler
    where TVirtualView : IView
    where TPlatformView : class
{
    new TVirtualView VirtualView { get; }
}

public interface ILayoutHandler<out TPlatformView> : IViewHandler<ILayout, TPlatformView>
    where TPlatformView : class
{
    void Add(IView view);
    void Remove(IView view);
    void Clear();
    void Insert(int index, IView view);
    void Update(int index, IView view);
    void UpdateZIndex(IView view);
}

Why this is the smallest change that covers everything: ElementHandler<TVirtualView, TPlatformView> and ViewHandler<TVirtualView, TPlatformView> now implement the matching interface. Their existing public VirtualView/PlatformView members already have exactly the right signatures, so no handler needed a new member — in the box or out of it. All 46 aliased handlers, and every third-party handler derived from ViewHandler<,>, satisfy the new contracts automatically. This is why the general solution was viable for net11 instead of only patching four interfaces.

TPlatformView is covariant, so object is the platform-neutral wildcard:

// Matches the in-box LabelHandler on every platform AND any external backend's label handler.
if (label.Handler is IViewHandler<ILabel, object> labelHandler)
{
    ILabel virtualView = labelHandler.VirtualView;
    object nativeLabel = labelHandler.PlatformView;
}

ILayoutHandler<TPlatformView> is deliberately not related to ILayoutHandler by inheritance. Relating them would force ILayoutHandler to hide the inherited members, breaking any type that implements Add/Remove/... as explicit interface implementations. Keeping them unrelated means a handler implementing those members as ordinary public methods — as in-box LayoutHandler does — satisfies both at once. LayoutHandler declares both.

Backward compatibility

  • No member moved off ILabelHandler, IContentViewHandler, ILayoutHandler or IWindowHandler.
  • No aliased interface gained or lost a base interface.
  • Property mappers, command mappers, handler registration, ToHandler/ToPlatform untouched.
  • Existing casts such as Handler as ILayoutHandler in the Controls compatibility layer are unchanged.

Verified empirically: derived handlers (class X : LabelHandler), and handlers implementing ILabelHandler/ILayoutHandler with explicit-only interface implementations, were compiled against Microsoft.Maui.Core 11.0.0-preview.7.26406.9 and then loaded against a build containing this change. All type-load without TypeLoadException and all existing is/cast relationships still hold.

One documented nuance: a pre-existing type that implements ILayoutHandler explicitly-only does not automatically become ILayoutHandler<object> (it never lists the interface). That is why nothing in MAUI was switched to check only the neutral form.

Follow-up coverage

The generic contracts cover every handler automatically, so no per-control follow-up is needed for recognition or typed access. Remaining, tracked separately:

  1. Other interfaces that carry behavior rather than accessors (e.g. IScrollViewHandler) can get the ILayoutHandler<TPlatformView> treatment on demand.
  2. Handler infrastructure still internal or TFM-locked: ViewHandler.ContainerView's setter, MauiContext.AddSpecific, LifecycleEventServiceExtensions.InvokeLifecycleEvents, Microsoft.Maui.Handlers.LayoutExtensions, HandlerNotFoundException. Those are separate from the interface-shape problem.

Issues Fixed

Unblocks external platform backends (for example a standalone Tizen backend) that were blocked on gap G2: handler interfaces binding PlatformView to a per-TFM alias.

Tests

  • src/Core/tests/ExternalBackend (new) — Microsoft.Maui.Core.ExternalBackend.TestAssembly, deliberately absent from Core's InternalsVisibleTo and built with TreatWarningsAsErrors=true. Contains fake native view types (FakeNativeLabel, FakeNativeLayoutView, FakeNativeContentView, FakeNativeWindow) and handlers for label, content view, layout and window. Everything it compiles is therefore provably public API and provably warning-free for an external consumer.
  • src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs (new, 18 tests) — contract satisfaction for external and in-box handlers, covariance, ILayoutHandler shape unchanged, external handler resolved through handler registration, property-mapper composition off ViewHandler.ViewMapper, and Controls' Layout Add/Insert/RemoveAt/indexer-set/Clear command routing reaching an external layout handler.

Validation run locally on net11.0:

Suite Result
Core.UnitTests 966 passed, 3 skipped, 0 failed
Controls.Core.UnitTests 6207 passed, 30 skipped, 0 failed
Core net11.0 / netstandard2.0 / netstandard2.1 with PublicApiType=Validate build succeeded
dotnet format --verify-no-changes on changed files clean

Platform TFMs (-android, -ios, -maccatalyst, -windows) are covered by CI; the required workloads are not installed on the machine used here.

Docs

docs/design/ExternalPlatformBackends.md documents the problem, the contracts, adoption steps for an external backend, and follow-up coverage.

Every per-control handler interface in Microsoft.Maui.Core declares PlatformView
through a `using PlatformView = ...` alias that resolves to a different native
type per target framework. That bakes MAUI's own native types into the compiled
contract, so a platform backend shipping outside dotnet/maui - which owns its own
native types - cannot implement them:

  - CS0738 on a platform TFM, where the alias is one of MAUI's native types.
  - CS9333 (plus CS8766, an error under TreatWarningsAsErrors) on the neutral
    net11.0 TFM, where the alias is a non-nullable System.Object.

Both were reproduced against Microsoft.Maui.Core 11.0.0-preview.7.26406.9.

Adds three additive interfaces that carry the same strong typing without the
alias:

  - Microsoft.Maui.IElementHandler<out TVirtualView, out TPlatformView>
  - Microsoft.Maui.IViewHandler<out TVirtualView, out TPlatformView>
  - Microsoft.Maui.ILayoutHandler<out TPlatformView>

ElementHandler<,> and ViewHandler<,> implement the matching interface. Their
existing public VirtualView/PlatformView members already have the right
signatures, so no handler - in the box or out of it - needed a new member, and
all 46 aliased handlers are covered at once. TPlatformView is covariant, so
`IViewHandler<ILabel, object>` matches any label handler from any backend.

ILayoutHandler<TPlatformView> carries the child-management behavior that only
ILayoutHandler had. It is deliberately unrelated to ILayoutHandler by
inheritance: relating them would force member hiding and break explicit
interface implementations. LayoutHandler declares both.

Nothing was moved, renamed or removed. Binary compatibility was verified by
compiling derived and explicit-interface-implementation handlers against
11.0.0-preview.7.26406.9 and loading them against this build.

Adds src/Core/tests/ExternalBackend, a separate assembly that is absent from
Core's InternalsVisibleTo and builds with TreatWarningsAsErrors, so everything it
compiles is provably public and warning-free for an external consumer. Tests
cover contract satisfaction, covariance, handler registration, mapper
composition off ViewHandler.ViewMapper, Controls' Layout command routing into an
external layout handler, and that the aliased interfaces are unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings August 26, 2026 20:10
@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:10 — with GitHub Actions Inactive
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37855

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37855"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:11 — with GitHub Actions Inactive
@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:12 — with GitHub Actions Inactive
@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:14 — with GitHub Actions Inactive
@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:15 — with GitHub Actions Inactive
@github-actions github-actions Bot added the area-core-platform Integration with platforms label Aug 26, 2026
@Redth
Redth temporarily deployed to copilot-pat-pool August 26, 2026 20:15 — with GitHub Actions Inactive

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds new public, platform-neutral generic handler contracts (IElementHandler<,>, IViewHandler<,>, ILayoutHandler<>) so external platform backends (shipping outside dotnet/maui) can participate in MAUI’s strongly-typed handler APIs using their own native view types. It updates the generic handler base classes to implement these contracts, adds an external-backend test assembly to validate consumption from a non-InternalsVisibleTo consumer, and documents adoption guidance.

Changes:

  • Introduces new public generic handler interfaces in Microsoft.Maui to avoid per-TFM PlatformView aliases blocking external implementations.
  • Updates ElementHandler<TVirtualView, TPlatformView>, ViewHandler<TVirtualView, TPlatformView>, and LayoutHandler to satisfy the new contracts.
  • Adds an “external backend” test project plus unit tests and design documentation to validate the contracts and backward compatibility.

Reviewed changes

Copilot reviewed 25 out of 25 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/Core/src/Handlers/IElementHandlerOfT.cs Adds IElementHandler<TVirtualView, TPlatformView> generic contract for typed VirtualView/PlatformView.
src/Core/src/Handlers/IViewHandlerOfT.cs Adds IViewHandler<TVirtualView, TPlatformView> generic contract for typed view handlers (covariant).
src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs Adds ILayoutHandler<TPlatformView> generic behavior contract for layout child management without aliased platform types.
src/Core/src/Handlers/Element/ElementHandlerOfT.cs Updates generic ElementHandler<,> base class to implement IElementHandler<,>.
src/Core/src/Handlers/View/ViewHandlerOfT.cs Updates generic ViewHandler<,> base class to implement IViewHandler<,>.
src/Core/src/Handlers/Layout/LayoutHandler.cs Declares in-box LayoutHandler implements both legacy ILayoutHandler and new ILayoutHandler<PlatformView>.
src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj Adds external-consumer test assembly (warning-free, not in InternalsVisibleTo) targeting $(_MauiDotNetTfm).
src/Core/tests/ExternalBackend/FakeNativeViews.cs Provides backend-owned “native” types for external-backend tests.
src/Core/tests/ExternalBackend/FakeHandlers.cs Implements fake label/content/window handlers derived from MAUI generic bases, exercising the new contracts.
src/Core/tests/ExternalBackend/FakeLayoutHandler.cs Implements fake external ILayoutHandler<TPlatformView> plus command mapper wiring to match Controls layout commands.
src/Core/tests/ExternalBackend/ExternalBackendContracts.cs Adds compile-time contract assertions proving implicit conversions/covariance for external consumers.
src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs Adds unit tests validating contract satisfaction, covariance, handler registration, mapper composition, and legacy interface stability.
src/Core/tests/UnitTests/Core.UnitTests.csproj References the new external-backend test assembly from Core unit tests.
src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net PublicAPI baseline.
src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt Records new public generic interfaces/members in netstandard PublicAPI baseline.
src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt Records new public generic interfaces/members in netstandard2.0 PublicAPI baseline.
src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net-android PublicAPI baseline.
src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net-ios PublicAPI baseline.
src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net-maccatalyst PublicAPI baseline.
src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net-windows PublicAPI baseline.
src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt Records new public generic interfaces/members in net-tizen PublicAPI baseline.
Microsoft.Maui.sln Adds the new external-backend test project to the main solution.
Microsoft.Maui-windows.slnf Includes the new external-backend test project in the Windows solution filter.
Microsoft.Maui-mac.slnf Includes the new external-backend test project in the Mac solution filter.
docs/design/ExternalPlatformBackends.md Documents the motivation, contracts, and adoption guidance for external platform backends.

The macOS CI legs build Microsoft.Maui-mac.slnf, and both solution filters
resolve against Microsoft.Maui-dev.sln - not Microsoft.Maui.sln, which is what
the Windows leg builds and what the new test project was added to.

Listing the project in the filters without adding it to the filtered solution
made solution load fail before restore:

  Microsoft.Maui-mac.slnf(1,1): error MSB4025: The project file could not be
  loaded. Data at the root level is invalid. Line 1, position 1.

Reproduced locally, where MSBuild reports the underlying cause directly:

  error MSB5028: Solution filter file at ".../Microsoft.Maui-mac.slnf" includes
  project "src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj" that is
  not in the solution file at ".../Microsoft.Maui-dev.sln".

Adds the project to Microsoft.Maui-dev.sln under the same test solution folder
as Core.UnitTests. Both filters and both solutions now load cleanly.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings August 26, 2026 21:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 26 out of 26 changed files in this pull request and generated 2 comments.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 26, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 3 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Aug 26, 2026
The external-backend test assembly only targeted the platform-neutral TFM, so it
only ever proved the CS9333/CS8766 half of the problem. The CS0738 half - where
the aliased interfaces pin PlatformView to one of .NET MAUI's own concrete native
types - only occurs on a platform TFM and was therefore untested.

Multi-targets Core.ExternalBackend across $(_MauiDotNetTfm);$(MauiPlatforms), so
the same external-backend sources are compiled against every target framework
Core ships.

The fake native view types become per-platform, because ViewHandler<,> constrains
TPlatformView differently per TFM:

  net11.0                    class                                (derives from nothing)
  net11.0-android            Android.Views.View                   Android.Views.View
  net11.0-ios/-maccatalyst   UIKit.UIView                         UIKit.UIView
  net11.0-windows            Microsoft.UI.Xaml.FrameworkElement   Controls.Panel

That mirrors reality: a real external backend's views do derive from the
platform's base view type. What makes it external is that its concrete types are
its own, and so are never the types the aliased interfaces are pinned to. That is
precisely the CS0738 case. ElementHandler<,> constrains TPlatformView only to
class everywhere, so the fake native window type stays a single shared definition.

Fake members are prefixed Fake (FakeText, FakeOpacity, FakeChildren) so one set of
handler sources compiles on every TFM without colliding with a real platform base
type's members - notably FrameworkElement.Opacity on Windows.

Adds ExternalBackendTfmContracts.cs, which compiles unchanged on every TFM and
asserts at compile time that the backend's own native type survives a round trip
through both the typed and neutral contracts, that the layout contract's behavior
is callable, and that the in-box handlers satisfy the same neutral contracts.

No product code changes: Microsoft.Maui and its PublicAPI files are untouched.

Verified locally: net11.0, net11.0-android37.0 and net11.0-maccatalyst26.5 all
build clean with TreatWarningsAsErrors; Core.UnitTests 966 passed / 0 failed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings August 27, 2026 01:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 31 out of 31 changed files in this pull request and generated no new comments.

Suppressed comments (3)

Previously missed (2) — in code that hasn't changed since the last review.

src/Core/src/Handlers/IElementHandlerOfT.cs:47

  • TVirtualView is only constrained to IElement, which allows structs and makes the generic VirtualView property lose the non-nullable reference-type intent (and diverges from ElementHandler<TVirtualView, ...> which requires class). Adding a class constraint better reflects MAUI handler usage and improves nullability flow for external consumers.
	public interface IElementHandler<out TVirtualView, out TPlatformView> : IElementHandler
		where TVirtualView : IElement
		where TPlatformView : class

src/Core/src/Handlers/IViewHandlerOfT.cs:37

  • TVirtualView is constrained to IView but not to class, which permits structs and weakens nullability flow for VirtualView compared to the base ViewHandler<TVirtualView, ...> constraint (class, IView). Adding class aligns the contract with actual handler implementations and provides clearer typing for external backends.
	public interface IViewHandler<out TVirtualView, out TPlatformView> : IElementHandler<TVirtualView, TPlatformView>, IViewHandler
		where TVirtualView : IView
		where TPlatformView : class

src/Core/tests/ExternalBackend/FakeLayoutHandler.cs:96

  • GetNativeChild uses MauiContext! (null-forgiving) and will throw a NullReferenceException if invoked while the handler is disconnected. Since this is meant to model external backend code, it's better to fail with a clear InvalidOperationException when MauiContext is null.
		FakeNativeView? GetNativeChild(IView view) =>
			view.ToHandler(MauiContext!).PlatformView as FakeNativeView;

@Redth

Redth commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Update: external-implementer coverage extended to every target framework

Two commits since the initial review request. Neither changes product code — Microsoft.Maui and all PublicAPI.Unshipped.txt files are byte-identical to 367520bce4, so the API review surface is unchanged.

56aaeb6085 — solution plumbing fix

Core.ExternalBackend.csproj was added to Microsoft.Maui.sln and to both .slnf filters, but not to Microsoft.Maui-dev.sln — which is what both filters actually resolve against ("path": "Microsoft.Maui-dev.sln"). The macOS legs build Microsoft.Maui-mac.slnf while the Windows legs build Microsoft.Maui.sln, so only macOS broke, with a misleading MSB4025: Data at the root level is invalid. Locally MSBuild names the real cause:

error MSB5028: Solution filter file ... includes project
"src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj" that is not in the
solution file at ".../Microsoft.Maui-dev.sln".

Fixed by adding the project to Microsoft.Maui-dev.sln. All four solution/filter files now load with 0 errors under -t:ValidateSolutionConfiguration.

9d4f2d326e — compile the external-backend tests on every TFM

The external-backend assembly previously targeted only net11.0, so it only proved the CS9333/CS8766 half of the problem. The CS0738 half — where the aliased interfaces pin PlatformView to one of .NET MAUI's own concrete native types — only occurs on a platform TFM and was untested. That is the case a real external backend actually hits.

Core.ExternalBackend now multi-targets $(_MauiDotNetTfm);$(MauiPlatforms), compiling identical external-backend sources on every target framework Core ships.

This surfaced a detail worth recording in review: ViewHandler<TVirtualView, TPlatformView> constrains TPlatformView differently per TFM, so the fake native view types are now per-platform:

Target framework ViewHandler<,> constraint Fake native view derives from
net11.0 class (nothing)
net11.0-android Android.Views.View Android.Views.View
net11.0-ios, -maccatalyst UIKit.UIView UIKit.UIView
net11.0-windows Microsoft.UI.Xaml.FrameworkElement Microsoft.UI.Xaml.Controls.Panel

This mirrors reality: a real external backend's views do derive from the platform's base view type — that constraint was never the blocker. What makes a backend external is that its concrete types are its own, and therefore never the types the aliased interfaces are pinned to (MauiLabel, AppCompatTextView, TextBlock). That mismatch is exactly CS0738.

ElementHandler<TVirtualView, TPlatformView> constrains TPlatformView only to class on every TFM, so the fake native window type stays a single shared definition.

Fake members are prefixed Fake (FakeText, FakeOpacity, FakeChildren) so one set of handler sources compiles on every TFM without colliding with real platform members — notably FrameworkElement.Opacity on Windows.

Also adds ExternalBackendTfmContracts.cs, which compiles unchanged on every TFM and asserts at compile time that the backend's own native type survives a round trip through both the typed and neutral contracts, that the layout contract's behavior is callable, and that the in-box handlers satisfy the same neutral contracts.

Validation

Target framework Result
net11.0 ✅ local, TreatWarningsAsErrors=true
net11.0-android37.0 ✅ local — CS0738 case proven closed
net11.0-ios26.5 ✅ local
net11.0-maccatalyst26.5 ✅ local
net11.0-windows10.0.19041 / .20348 ✅ CI — Build Windows (Debug) + (Release)
Core.UnitTests ✅ 966 passed / 0 failed / 3 skipped
Controls.Core.UnitTests ✅ 6207 passed / 0 failed
dotnet format --verify-no-changes ✅ clean

CI on build 1569571: 28 checks passing, 0 failing — including all macOS and Windows build legs, Pack macOS/Pack Windows, every integration leg, and Windows Helix Unit Tests (Debug) and (Release), which now both pass.

For the record, since earlier runs showed Helix red: those failures were a pre-existing net11.0 baseline infra issue, not this PR. Helix marked work items failed while every test passed and every work item exited 0 — e.g. Controls.Core.UnitTests Total: 6237, Errors: 0, Failed: 0, with the reporter logging Writing 0 test results … (JSON v1) right after packing 6237 reports. The same jobs were red on net11.0 across four consecutive base builds (1567261, 1568023, 1568713, 1568717) without this PR's commits, and the failing set was non-deterministic across runs. They are green on the current build.

Backward compatibility

Verified empirically, not just by inspection: handlers compiled against the released Microsoft.Maui.Core 11.0.0-preview.7.26406.9 — both derived subclasses (class X : LabelHandler) and explicit-interface-implementation handlers (ILabelHandler/ILayoutHandler implemented explicitly) — were loaded against a build containing this change. All type-load with no TypeLoadException and every existing is/cast relationship still holds.

One documented nuance, called out in docs/design/ExternalPlatformBackends.md: a pre-existing type that implements ILayoutHandler with explicit-only interface implementations does not automatically satisfy ILayoutHandler<object>, since it never lists the interface. That is why nothing in .NET MAUI was switched to check only the neutral form.

Ready for final code and API review.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 1279cef0-092d-4b50-9497-8565b890e8de
Copilot AI review requested due to automatic review settings August 28, 2026 00:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 29 out of 29 changed files in this pull request and generated no new comments.

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

src/Core/tests/ExternalBackend/FakeLayoutHandler.cs:94

  • UpdateZIndex will add a child that was never part of FakeChildren (because Remove is a no-op when the child isn't present, then Insert always runs). This diverges from in-box layout handlers, which no-op when the native child isn't currently in the container, and can cause incorrect state (duplicates) if UpdateZIndex is invoked out of order.
			if (view.Handler?.PlatformView is FakeNativeView child)
			{
				List<FakeNativeView> children = PlatformView.FakeChildren;
				children.Remove(child);
				children.Insert(GetClampedZIndex(view, children.Count), child);

src/Core/tests/ExternalBackend/FakeHandlers.cs:79

  • FakeContentViewHandler.MapContent reads the presented content's existing Handler?.PlatformView but never realizes a handler/platform view for the content. In-box handlers (e.g., ContentViewHandler) create/update the platform view from PresentedContent via the handler's MauiContext, so this implementation can silently leave FakeContent null even when content exists.
		public static void MapContent(FakeContentViewHandler handler, IContentView contentView)
		{
			handler.PlatformView.FakeContent =
				(contentView.PresentedContent as IView)?.Handler?.PlatformView as FakeNativeView;
		}

@Redth

Redth commented Aug 28, 2026

Copy link
Copy Markdown
Member Author

@kubaflo narrow current-head review request for d94349c85d26202453329985c52dd019a7874c28 (CI merge 21bdc985 = base 48d45a5 + head d94349c).

The product contracts and approved external-backend test sources remain unchanged from 5d65992; d94349c only removes the unused import raised in the current-head Copilot review. All six inline threads are resolved.

Validation: 29/29 external-backend tests pass; Core PublicAPI validation passes on net11.0, netstandard2.0, and netstandard2.1; the Android external-backend contract build passes with warnings-as-errors; formatting is clean. The final CI run also passed Build macOS Release and iOS NativeAOT, so the prior AAPT/JDK failures recovered and are not persistent branch regressions.

The remaining red checks in PR build 1571645 are evidence-backed outside this PR:

  • Build integration on macOS and Windows fails the same three AspireServiceDefaultsTemplateUsesCorrectProjectName cases with the same UseMauiCore / NU1015 reason on the exact base build 1571504.
  • Helix Release fails in Microsoft.Maui.Resizetizer.UnitTests; this PR has no Resizetizer delta, recent base builds fail different tests in the same suite, and Build Analysis reports the current test at a 0.10% historical failure rate.

CI is therefore not numerically green because the exact base is red, but I found no PR-specific failing leg. Could you please review only the merge/current-head delta and refresh your review, and dismiss the stale MauiBot CHANGES_REQUESTED review pinned to 56aaeb6?

@Redth
Redth requested a review from kubaflo August 28, 2026 02:41
@kubaflo

kubaflo commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Multi-model merge-safety recheck at 792caa64c8ae1965d990fc4965db330b7d6edbd8: SAFE TO MERGE, with a prominent non-blocking documentation fix.

This head is a pure merge of the previously reviewed d94349c8 head with current net11.0 at 533bb4aa. Claude Opus 5 reviewed the merge in both directions, and GPT-5.6 Terra reran the affected proof on the exact merge head.

Empirical and merge-integrity results:

  • 41/41 targeted tests passed: 18 external-platform contract tests, 8 target-framework drift tests, and 15 container-lifecycle tests.
  • The shared Core.ExternalBackend project built cleanly for net11.0, netstandard2.0, and netstandard2.1, each with zero warnings and zero errors.
  • All 21 PR-owned non-PublicAPI source, test, project, and design-document blobs are byte-identical to d94349c8.
  • The only shared merge surface is the eight Core PublicAPI.Unshipped.txt files. Exact three-way set checks found zero lost lines, zero extra lines, and zero duplicates: all 12 generic-handler entries remain in every file, alongside both newly landed toolbar entries.
  • The symmetric incoming-side check found all 44 target-branch files preserved: 36 are byte-identical to 533bb4aa, and the other eight are the already-proven lossless PublicAPI unions. All five solution/filter registrations and the shared external-backend project wiring remain intact.

The new MauiBot documentation finding is real but does not expose a defect in the generic contracts. A temporary six-case non-friend harness proved that an external handler following the XML/IntelliSense example and calling base(WindowHandler.Mapper) compiles but throws InvalidCastException when the mapper casts it to IWindowHandler; analogous in-box layout mapper reuse casts to ILayoutHandler. Backend-owned, correctly typed window and layout mapper controls pass, matching this PR's tests and design document. The relevant mapper and example blobs are unchanged at 792caa64, so that causal result carries forward exactly.

Please promptly replace the unsafe base(WindowHandler.Mapper) IntelliSense example with a backend-owned PropertyMapper<IWindow, MyWindowHandler> chained from ElementHandler.ElementMapper. The layout observation is an inherent limitation of platform-specific in-box mappers, not a new product defect, so this remains a prominent follow-up rather than a merge blocker under a pragmatic threshold.

The title remains accurate. Minor body cleanup also remains: it names ExternalBackend.TestAssembly instead of TestSupport, describes the pre-existing external-backend folder as wholly new, retains the container-setter gap already closed by #37854, and has stale test counts.

Current-head CI has finished with 28 successful checks and three reds. Two reds are aggregate maui-pr/Build Analysis checks; the only failing leaf is the Helix monitor. I inspected its raw Azure log and both work-item consoles: Windows Debug failed SkiaSharpSvgToolsTests.Resize.BasicNoScaleReturnsOriginalSize while deleting a temporary file held by another process, and Windows Release failed ResizetizeImagesTests.ExecuteForiOS.SingleVectorAppIconWithOnlyPathSucceedsWithVectors while recursively cleaning an output directory containing a locked PNG. Each Resizetizer assembly ran 762 tests with one failure and two skips; the corresponding macOS-hosted Debug and Release jobs passed all ten work items. This merge-only head changes no Resizetizer source or tests, so those transient cleanup locks are unrelated to #37855. Every other leaf check passed.

Local validation used SDK 11.0.100-preview.6.26359.118 rather than the repo's RC.1. No physical Apple device, Mac Catalyst, or UI execution was used.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 2 findings

See inline comments for details.

/// // In an external platform backend, with a native type MAUI knows nothing about:
/// public class MyWindowHandler : ElementHandler<IWindow, MyNativeWindow>
/// {
/// public MyWindowHandler() : base(WindowHandler.Mapper) { }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Public API Surface Design / Logic and Correctness — The documented example for external backends passes an in-box control-specific mapper (base(WindowHandler.Mapper)) to a handler that only implements the new generic contract. WindowHandler.Mapper is IPropertyMapper<IWindow, IWindowHandler> (src/Core/src/Handlers/Window/WindowHandler.cs:17) and PropertyMapper<TVirtualView, TViewHandler>.Add invokes each mapping via a hard cast action?.Invoke((TViewHandler)h, vv) (src/Core/src/PropertyMapper.cs:239); CommandMapper<,> does the same (src/Core/src/CommandMapper.cs:102). MyWindowHandler : ElementHandler<IWindow, MyNativeWindow> does not implement IWindowHandler — that is precisely the alias problem this PR works around — so the first property update (e.g. Title) throws InvalidCastException at runtime. Concrete scenario: an external backend follows this doc verbatim, and the window crashes on its first mapper run. No test covers it: every fake in src/Core/tests/ExternalBackend/FakeHandlers.cs declares its own PropertyMapper<TVirtualView, FakeXHandler> chained off ElementMapper/ViewMapper (whose handler type parameters — IElementHandler/IViewHandler — the fakes do satisfy), so the mapper-reuse path the doc recommends is never exercised. The example should either build a backend-owned mapper (as the fakes do) or explicitly state that in-box control-specific mappers cannot be reused by a handler that does not implement the corresponding aliased handler interface.

/// <para>
/// <b>Known gap.</b> The obsolete
/// <c>Microsoft.Maui.Controls.Compatibility.Layout&lt;T&gt;.LayoutHandler</c> property is declared as
/// <see cref="ILayoutHandler"/> and evaluates <c>Handler as ILayoutHandler</c>, so it returns

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[moderate] Public API Surface Design / Backward Compatibility — The "Known gap" paragraph states the obsolete Compatibility.Layout<T>.LayoutHandler property "is the sole runtime cast to ILayoutHandler left in .NET MAUI". That is not accurate, and the inaccuracy points at a real runtime failure mode for the scenario this interface exists to enable: LayoutHandler.Mapper / LayoutHandler.CommandMapper are declared as PropertyMapper<ILayout, ILayoutHandler> / CommandMapper<ILayout, ILayoutHandler> (src/Core/src/Handlers/Layout/LayoutHandler.cs:22,31), and both cast the handler to ILayoutHandler when a mapping runs (src/Core/src/PropertyMapper.cs:239, src/Core/src/CommandMapper.cs:102). An external-backend layout handler that implements only ILayoutHandler<TPlatformView> and reuses those in-box mappers throws InvalidCastException on the first Add/Background mapping, even though the Controls-side Handler.Invoke(nameof(ILayoutHandler.Add), ...) key path described just above is indeed type-agnostic. (src/Core/tests/DeviceTests/Stubs/LayoutStub.cs:13 is a second Handler as ILayoutHandler.) The remark should be corrected to "the sole runtime cast in shipping non-obsolete product code is …" and should call out that the in-box layout mappers are ILayoutHandler-typed and therefore cannot be reused by a handler implementing only the generic interface — which is what FakeLayoutHandler (src/Core/tests/ExternalBackend/FakeLayoutHandler.cs:26-37) demonstrates by declaring its own mappers.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review Summary

@Redth — new AI review results are available based on commit d94349c.

Gate Inconclusive Confidence High Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ⚠️ INCONCLUSIVE

Platform: ANDROID · Base: net11.0 · Merge base: e4b0c0a1

🩺 Base branch does not compile — the without-fix build failed. The gate's "does the test fail without the fix" check is unreliable here; this usually means main is broken or a merge-base file went missing. Note: this PR ADDS 3 new file(s), which the gate removes to reconstruct the pre-fix baseline; if the PR's own (never-reverted) test files reference types defined in those new files, the baseline cannot compile — that reflects a new-feature PR the gate cannot isolate a "before" state for, not necessarily a broken main. The with-fix result below is the reliable signal. Investigate before trusting this gate.

/home/vsts/work/1/s/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs(24,79): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tes...

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 ExternalBackendTargetFrameworkTests ExternalBackendTargetFrameworkTests 🛠️ BUILD ERROR ✅ PASS — 47s
🧪 ExternalPlatformBackendTests ExternalPlatformBackendTests 🛠️ BUILD ERROR ✅ PASS — 13s
🔴 Without fix — 🧪 ExternalBackendTargetFrameworkTests: 🛠️ BUILD ERROR · 59s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs(24,79): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(18,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(24,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(27,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(30,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(33,17): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(36,17): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(42,17): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(45,17): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(51,44): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(56,50): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(61,45): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(72,51): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(82,41): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
🟢 With fix — 🧪 ExternalBackendTargetFrameworkTests: PASS ✅ · 47s

(no coded error found; showing last 1200 chars)

Tests.dll (.NETCoreApp,Version=v11.0)
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 11.0.0-rc.1.26379.102)
[xUnit.net 00:00:00.18]   Discovering: Microsoft.Maui.UnitTests
[xUnit.net 00:00:00.63]   Discovered:  Microsoft.Maui.UnitTests
[xUnit.net 00:00:00.64]   Starting:    Microsoft.Maui.UnitTests
[xUnit.net 00:00:00.75]   Finished:    Microsoft.Maui.UnitTests
  Passed EveryPlatformHasFakeNativeViewSources(fileName: "FakeNativeViews.Android.cs") [5 ms]
  Passed EveryPlatformHasFakeNativeViewSources(fileName: "FakeNativeViews.Tizen.cs") [< 1 ms]
  Passed EveryPlatformHasFakeNativeViewSources(fileName: "FakeNativeViews.iOS.cs") [< 1 ms]
  Passed EveryPlatformHasFakeNativeViewSources(fileName: "FakeNativeViews.Standard.cs") [< 1 ms]
  Passed EveryPlatformHasFakeNativeViewSources(fileName: "FakeNativeViews.Windows.cs") [< 1 ms]
  Passed ExternalBackendInheritsThePlatformSetFromMauiPlatforms [8 ms]
  Passed ExternalBackendCompilesNetStandardTargetFrameworks [2 ms]
  Passed ExternalBackendMirrorsCoreTargetFrameworks [1 ms]
Test Run Successful.
Total tests: 8
     Passed: 8
 Total time: 1.8120 Seconds
🔴 Without fix — 🧪 ExternalPlatformBackendTests: 🛠️ BUILD ERROR · 12s

Error-relevant lines (filtered from the build log):

/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(18,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(24,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(27,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(30,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(33,17): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(36,17): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(42,17): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(45,17): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(51,44): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(56,50): error CS0308: The non-generic type 'IElementHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(61,45): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(72,51): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(82,41): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
/home/vsts/work/1/s/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs(24,79): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj::TargetFramework=net11.0]
🟢 With fix — 🧪 ExternalPlatformBackendTests: PASS ✅ · 13s

(no coded error found; showing last 1200 chars)

 [< 1 ms]
  Passed InBoxWindowHandlerSatisfiesPlatformNeutralContract [1 ms]
  Passed ExternalViewHandlerSatisfiesTypedNeutralContract [5 ms]
  Passed ExternalElementHandlerSatisfiesPlatformNeutralContract [< 1 ms]
  Passed ExternalHandlerIsReachableThroughPlatformNeutralContract [280 ms]
  Passed ExternalHandlerIsResolvedThroughHandlerRegistration [4 ms]
  Passed ExternalLayoutHandlerIsDrivenThroughNeutralContract [12 ms]
  Passed ExternalViewHandlerSatisfiesPlatformNeutralContract [< 1 ms]
[xUnit.net 00:00:01.29]   Finished:    Microsoft.Maui.UnitTests
  Passed ExternalHandlerInheritsViewMapperFromCore [10 ms]
  Passed InBoxLabelHandlerSatisfiesPlatformNeutralContract [< 1 ms]
  Passed ExternalWindowHandlerRunsThroughElementMapper [17 ms]
  Passed ExternalHandlerDoesNotImplementAliasedInterface [2 ms]
  Passed ControlsLayoutCommandsReachExternalLayoutHandler [57 ms]
  Passed PlatformNeutralContractsAreCovariant [< 1 ms]
  Passed AliasedLayoutHandlerContractIsUnchanged [6 ms]
  Passed ExternalHandlerPropertyMapperUpdatesNativeView [< 1 ms]
  Passed InBoxLayoutHandlerSatisfiesBothLayoutContracts [1 ms]
Test Run Successful.
Total tests: 18
     Passed: 18
 Total time: 2.3131 Seconds

⚠️ Failure Details

  • 🛠️ ExternalBackendTargetFrameworkTests without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs(24,79): error CS0308: The non-generic type 'ILayoutHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Core/tes...
  • 🛠️ ExternalPlatformBackendTests without fix: build failed before tests could run
    • /home/vsts/work/1/s/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs(18,17): error CS0308: The non-generic type 'IViewHandler' cannot be used with type arguments [/home/vsts/work/1/s/src/Cor...
📁 Fix files reverted (11 files)
  • src/Core/src/Handlers/Element/ElementHandlerOfT.cs
  • src/Core/src/Handlers/Layout/LayoutHandler.cs
  • src/Core/src/Handlers/View/ViewHandlerOfT.cs
  • src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt
  • src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt

New files (not reverted):

  • src/Core/src/Handlers/IElementHandlerOfT.cs
  • src/Core/src/Handlers/IViewHandlerOfT.cs
  • src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs

📋 Pre-Flight — Context & Validation

PR #37855 Pre-Flight

Context

  • Title: [net11.0] Add platform-neutral handler contracts for external platform backends
  • Author / branch: Redth:redth-external-handler-interface-contracts
  • Base: net11.0 at merge base e4b0c0a1fb
  • Materialized review commit: cf9ee66d4d
  • Scope: 29 files, +1891/-6. The PR adds three generic public contracts:
    IElementHandler<TVirtualView,TPlatformView>,
    IViewHandler<TVirtualView,TPlatformView>, and
    ILayoutHandler<TPlatformView>.
  • Problem: Existing per-control handler interfaces compile PlatformView to a
    target-specific alias. An out-of-tree backend with its own native types therefore
    cannot implement those interfaces (CS0738 on platform TFMs and CS9333/CS8766
    on neutral TFMs).

Existing fix

The PR makes ElementHandler<TVirtualView,TPlatformView> and
ViewHandler<TVirtualView,TPlatformView> implement the new covariant generic
contracts, and makes the in-box LayoutHandler also implement
ILayoutHandler<PlatformView>. The existing public members satisfy the contracts;
no mapper or handler lifecycle behavior changes. ILayoutHandler<TPlatformView> is
intentionally separate from the existing aliased ILayoutHandler so explicit-only
third-party implementations are not broken.

The PR also:

  • records the APIs in all PublicAPI.Unshipped.txt surfaces;
  • adds a multi-target external-backend test assembly with non-MAUI native types;
  • adds runtime contract/mapper/layout-command tests and target-framework drift tests;
  • documents covariance, disconnected-handler throwing behavior, Controls command
    mapper interoperability, and the obsolete compatibility-layout limitation.

Prior review evidence

Earlier review findings covered disconnected-handler nullability documentation,
the obsolete compatibility layout cast, and missing platform-TFM compile coverage.
The current head addresses them with guarded examples/lifecycle docs, explicit
documentation and end-to-end layout command coverage, plus a guard project that
mirrors Core's full TFM expression. No unresolved inline finding was identified in
the current public discussion. The mechanical regression cross-reference is clean.

Test boundary

The gate is INCONCLUSIVE only for its reconstructed without-fix baseline because
the PR's retained tests reference the three new source files removed by gate
reconstruction. The with-fix runs passed:

  • Primary: ExternalPlatformBackendTests — 18/18 passed.
  • Mandatory regression: ExternalBackendTargetFrameworkTests — 8/8 passed.

Do not rerun the gate. For each alternative candidate, run only:

dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --no-restore \
  --filter "FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalPlatformBackendTests|FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalBackendTargetFrameworkTests"

No full suite is permitted. Target platform context is Android, but these detected
tests are filtered unit tests.

Try-fix constraints

  • Candidate 1 must differ from the PR's generic-contract-on-base-handler strategy.
  • Candidate 2 must also differ at the mechanism level from candidate 1.
  • The try-fix restoration protocol controls the worktree. The current workspace
    contains extensive pre-existing harness changes under .github/ and eng/;
    do not alter, restore, clean, stash, or delete them.
  • The PR adds production source files. If
    EstablishBrokenBaseline.ps1 records any NewFiles, the try-fix skill requires
    the attempt to be recorded as Blocked without editing tracked files, followed
    by its mandatory script-only restore.

🔬 Code Review — Deep Analysis

Expert Evaluation — PR #37855

Verdict: NEEDS_DISCUSSION
Confidence: High for the two documentation findings; medium for the overall implementation because the expert pass did not independently compile the multi-TFM matrix.

Assessment

The submitted API design is sound and additive. The new covariant
IElementHandler<TVirtualView, TPlatformView>,
IViewHandler<TVirtualView, TPlatformView>, and
ILayoutHandler<TPlatformView> contracts avoid the platform-alias type-identity
problem without changing the existing aliased interfaces. Existing
ElementHandler<,>, ViewHandler<,>, and LayoutHandler properties satisfy the
new contracts, the generic constraints are variance-safe, and the PublicAPI
entries are consistent across target frameworks. No Android-specific type or
lifecycle defect was found.

The Gate is inconclusive only for its reconstructed without-fix baseline. Its
retained with-fix evidence reports 18/18 primary tests and 8/8 target-framework
regression tests passing; neither blocked try-fix candidate produced executable
evidence.

Findings

  1. Major — the external window-handler example recommends an incompatible mapper.
    src/Core/src/Handlers/IElementHandlerOfT.cs:48 constructs a handler that
    implements only the new neutral contract with WindowHandler.Mapper.
    WindowHandler.Mapper is typed to IWindowHandler, and mapper invocation
    casts the handler to that aliased interface. A backend following the example
    will therefore receive InvalidCastException on its first mapped property
    update. The example should use a backend-owned mapper chained from
    ElementHandler.ElementMapper, and the documentation should distinguish
    reusable neutral base mappers from in-box control-specific mappers.

  2. Moderate — the layout remarks overstate the remaining cast boundary.
    src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs:35 calls the obsolete
    compatibility property the sole remaining runtime cast to
    ILayoutHandler. LayoutHandler.Mapper and LayoutHandler.CommandMapper
    are also typed to the aliased interface and cast during invocation, and
    LayoutStub contains another cast. The remarks should preserve the valid
    Controls command-key explanation while explicitly warning that the in-box
    layout mappers cannot be reused by a handler implementing only the generic
    interface.

Consolidated Reviewer Recommendation

Apply one documentation-only patch that replaces the invalid example with a
backend-owned mapper and corrects the mapper/cast guidance for both element and
layout handlers. The public API and implementation do not need redesign.


🛠️ Try-Fix — Analysis & Comparison

Try-Fix Aggregate — PR #37855

Candidates completed: 2. Latest status: candidate 2 = Blocked (0 self-review findings, no files changed). Candidate 2 is the final bounded attempt.


Try-Fix Candidate 1 — PR #37855

Result: Blocked · Self-review findings: 0 · Attempt artifacts: CustomAgentLogsTmp/PRState/37855/PRAgent/try-fix/attempt-1/

Approach

Default-Interface-Member (DIM) Bridge on the Neutral Contracts — designed but NOT applied; the attempt was Blocked at Step 2 before any tracked edit.

Declare the same three platform-neutral contract type names the retained tests require
(IElementHandler<TVirtualView, TPlatformView>, IViewHandler<TVirtualView, TPlatformView>,
ILayoutHandler<TPlatformView>), but supply the strongly typed VirtualView/PlatformView
members as default interface members whose bodies project the already-existing nullable,
alias-free, non-generic IElementHandler.VirtualView / IElementHandler.PlatformView — instead
of leaving them as abstract interface members that each handler class must satisfy with its own
alias-typed property.

Under this mechanism the generic base handlers (ElementHandler<,>, ViewHandler<,>,
LayoutHandler) are not edited at all: no handler adds the new interfaces to its base list,
no handler re-declares a PlatformView member, and no PublicAPI.Unshipped.txt base-list entry
changes for existing types.

Prior approach avoided

The PR head (the existing fix) adds the same three covariant generic contracts and then
implements them on the in-box generic base handler classes:

  • ElementHandler<TVirtualView, TPlatformView> : …, IElementHandler<TVirtualView, TPlatformView>
  • ViewHandler<TVirtualView, TPlatformView> : …, IViewHandler<TVirtualView, TPlatformView>
  • LayoutHandler : ILayoutHandler, ILayoutHandler<PlatformView>

Its root-cause hypothesis is "external backends lack an alias-free contract to implement, so add
one and have the in-box base classes implement it."
The shared failure mechanism it targets is
that an implementing member's return type must exactly match the interface member's alias-resolved
PlatformView type — producing CS0738 on platform TFMs and CS9333/CS8766 on the neutral TFM. Its
residual weakness, and the reason a different mechanism is worth probing, is that conformance is
inherited only through the in-box generic base classes: a backend handler that does not derive
from ElementHandler<,> / ViewHandler<,> (legacy or hand-rolled) still gets nothing, and the
public base lists plus all 8 PublicAPI.Unshipped.txt surfaces must move in lockstep.

Mechanism-level difference

The PR removes the alias mismatch by adding a second contract that alias-free base classes
implement
. This candidate removes the alias mismatch by removing the need for any implementer to
declare a typed PlatformView member at all
.

Cause-to-effect chain: CS0738/CS9333/CS8766 are emitted only when a class supplies a member
whose declared return type must equal an interface member's alias-resolved type. If the typed
members are default interface members whose bodies cast the already-neutral
IElementHandler.PlatformView (declared object?, never alias-bound) to TPlatformView, then no
implementing class ever supplies a matching member, so the exact-return-type rule is never
evaluated, so the diagnostic cannot be produced — for in-box handlers, for external backends
derived from MAUI bases, and for hand-rolled handlers alike. The type-identity check moves from
compile-time member matching into a single cast inside the contract itself, and the in-box base
classes stay untouched. That is a different root-cause hypothesis ("the blocker is that
implementers must re-declare alias-typed members at all"
), not a relocation of the PR's
generic-interface logic.

Files changed

None. No tracked file was modified. Verified before and after with
git status --short -- src/ docs/ → empty.

Captured diff

Explicitly empty. fix.diff and reviewer-findings.diff are both 0 bytes. They were captured
with git diff -- src/ docs/ rather than a bare git diff, so the ~58 files of pre-existing
harness drift under .github/ and eng/ (which this attempt did not create and must not be
credited with) are excluded and "this attempt changed nothing" is verifiable.

Test command and results

Mandated command (primary + mandatory regression, run together, nothing else):

dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --no-restore \
  --filter "FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalPlatformBackendTests|FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalBackendTargetFrameworkTests"

Not executed. With no fix applied, the run would have measured the unmodified PR head — which
the gate already recorded as passing 18/18 and 8/8 — and the result would have been falsely
attributed to this candidate's mechanism. No partial, inferred, or manufactured result is claimed.
Full rationale is recorded in attempt-1/test-output.log.

Failure analysis (why Blocked)

Step 2 (Establish Baseline) failed hard:

pwsh .github/scripts/EstablishBrokenBaseline.ps1
→ "ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline"  (exit code 1)

The script enumerated ~58 pre-existing modified/deleted files under .github/scripts/,
.github/skills/, and eng/scripts/. Those are harness-owned changes this run is explicitly
forbidden to clean, stash, reset, restore, or commit — and the script's only offered remedies
(git checkout -- . or committing) are exactly those forbidden actions. No
.github/.baseline-state.json was produced.

Per try-fix skill principle 7 (Baseline-file boundary), the absence of that state file means there
is no RevertedFiles allow-list, so no tracked file may be edited and the attempt must be
recorded as Blocked before any tracked edit.

The same principle would have forced Blocked even on a pristine worktree: PR #37855 adds three
production source files (src/Core/src/Handlers/IElementHandlerOfT.cs,
src/Core/src/Handlers/IViewHandlerOfT.cs, src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs),
so the baseline state's NewFiles array would have been non-empty, and added production files are
not safely restorable by the script.

This is an environment/protocol constraint. It is not evidence for or against the DIM-bridge
mechanism, which remains untested.

Self-review

0 findings (reviewer-findings.json = []). The reviewed diff is empty, so there is nothing
to evaluate against the maui-expert-reviewer overarching principles or the always-active
dimensions (Logic and Correctness, Regression Prevention, Complexity Reduction). The Step 7.5 drift
check is trivially satisfied — the diff was empty at Step 6 and remained empty, so no refresh was
required.

Restore confirmation

Script-only restore executed exactly as required:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
→ Message: "No baseline state found"   Restored: False

This is the skill-sanctioned outcome for the verified no-state path: Step 2 never created baseline
state and no attempt edits were made. No git checkout / restore / reset / clean / stash
was used at any point, and all pre-existing untracked and modified harness paths under .github/
and eng/ were left exactly as found.

Guidance for candidate 2

  1. EstablishBrokenBaseline.ps1 is unusable in this workspace while the .github/ + eng/ drift
    is present. Candidate 2 will hit the identical exit-1 dirty-worktree abort — expect Blocked
    and do not burn cycles re-running it.
  2. Every candidate here is structurally blocked from editing tracked product files, independent of
    its mechanism's merits. Record the distinct mechanism, capture artifacts, restore via script.
  3. The retained tests reference the three new contract type names directly, so any viable
    alternative must still produce those exact public type names. The design freedom is in how
    conformance is established
    , not in renaming or relocating the contracts.
  4. Mechanism-space already consumed: (a) PR head — covariant generic contracts implemented on
    the in-box generic base handlers; (b) candidate 1 — same contract names, conformance supplied
    by default interface members bridging the alias-free non-generic IElementHandler members, zero
    edits to handler base lists. Candidate 2 must differ from both — e.g. attack the alias itself
    (per-TFM source-generated partial contract emission), or use an external adapter/wrapper that
    never requires the backend to implement a MAUI-declared typed member.

Structured result

Field Value
approach DIM-bridge conformance for the platform-neutral handler contracts (designed, not applied)
files_changed none
result Blocked
findings_count 0
status Done (not NeedsRetry — the block is deterministic, not transient)

Try-Fix Candidate 2 — PR #37855

Result: Blocked · Self-review findings: 0 · Attempt artifacts: CustomAgentLogsTmp/PRState/37855/PRAgent/try-fix/attempt-2/

Approach

Generic Per-Control Capability Interfaces — designed but NOT applied; the attempt was Blocked at Step 2 before any tracked edit.

Move platform neutrality to the interface layer where each target-specific alias is introduced. For an affected family, add an open generic sibling such as ILabelHandler<TPlatformView> : IViewHandler<ILabel, TPlatformView>, then make the existing compatibility interface inherit its in-box specialization: ILabelHandler : ILabelHandler<PlatformView>. An external backend explicitly implements ILabelHandler<MyNativeLabel>; its inherited public VirtualView and PlatformView properties satisfy that specialization. Existing in-box handlers continue implementing ILabelHandler and acquire the generic neutral contract through interface inheritance. Apply the same pattern to content-view, window, and layout families. ElementHandler<TVirtualView,TPlatformView>, ViewHandler<TVirtualView,TPlatformView>, and concrete LayoutHandler retain their original base lists.

Prior approaches avoided

The PR head adds abstract covariant generic contracts to the in-box generic handler base-class lists, so every derived handler receives conformance through implementation inheritance. Candidate 1 retained the same cross-cutting contracts but supplied their typed properties as default interface members casting the non-generic nullable handler surface, eliminating implementer members and handler base-list edits.

This candidate uses neither shared mechanism. It does not make generic base handlers implement the new interfaces, and it does not place executable bridge bodies or casts in interfaces. Instead, it opens the per-control alias-owning contract as a backend-selected generic specialization and preserves the existing aliased interface as the in-box closed specialization.

Mechanism-level difference

The root-cause hypothesis is that the problematic design choice is closing each per-control interface over MAUI's native alias, rather than missing conformance on generic handler bases (the PR) or requiring implementers to expose typed members (candidate 1). With an open per-control capability, the backend chooses TPlatformView at the point where the old API chose PlatformView. The implementing property's declared native type therefore already equals the selected interface return type, so CS0738/CS9333/CS8766 has no mismatched alias to compare. In-box conformance flows from old-interface → generic-interface inheritance; external conformance flows from an explicit generic per-control interface. No runtime cast and no DIM dispatch participates.

Critical viability assessment

The design is type-system viable and preserves existing non-generic interface names, but it is materially less viable as a product API than the PR's cross-cutting contracts. A complete solution needs a generic sibling and matching PublicAPI entries for every aliased handler family. Implementing only Label, ContentView, Window, and Layout to satisfy the retained tests would be a test-shaped, inconsistent API that does not solve the stated general external-backend problem. It also makes backend authors opt into each control capability rather than gaining conformance once from a common handler base. The required existing per-control interface files are outside this PR attempt's expected RevertedFiles boundary. These limitations are design evidence against the mechanism, but the attempt was procedurally Blocked before they could be compiled or measured.

Files changed

None. No tracked product or test file was edited. Before capture, git status --short -- src docs was empty and git diff -- src docs was 0 bytes.

Full captured diff

Explicitly empty. Both fix.diff and reviewer-findings.diff are 0 bytes. They capture the product/documentation scope (src/ and docs/) so the extensive pre-existing .github/ and eng/ harness drift is neither modified nor misattributed to candidate 2.

Exact test command and result

The mandatory primary and regression filters were to run together as:

dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj --no-restore --filter "FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalPlatformBackendTests|FullyQualifiedName~Microsoft.Maui.UnitTests.Handlers.ExternalBackendTargetFrameworkTests"

Not run. Baseline establishment produced no state/allow-list, so the hard bound required Blocked before any tracked edit. Running the command against the unchanged PR head would only repeat its already-known passing tests and falsely attribute that outcome to this unapplied candidate. attempt-2/test-output.log records this explicitly. No other tests, build, or gate command ran.

Failure analysis

The mandatory baseline command was invoked exactly once:

pwsh .github/scripts/EstablishBrokenBaseline.ps1
→ ERROR: DIRTY WORKING DIRECTORY - Cannot establish baseline (exit code 1)

It deterministically rejected the pre-existing modified/deleted harness files under .github/ and eng/. .github/.baseline-state.json was absent afterward, so there was no RevertedFiles absolute edit allow-list and NewFiles could not safely be evaluated. Per the baseline-file boundary and the user's hard bounds, candidate 2 was immediately Blocked from every tracked edit; the command was not retried. No clean, stash, reset, checkout, manual restore, or harness-path modification was performed.

Independently, a successful state would need to include every per-control interface and PublicAPI file required for a complete generic-sibling design. If it did not, this mechanism would still be Blocked rather than narrowed to the tests.

Self-review

0 findings (reviewer-findings.json is []). The final diff is empty. Inline review covered all eight overarching principles and the always-active Logic and Correctness, Regression Prevention, and Complexity Reduction dimensions. The Step 7.5 comparison confirmed the final diff remained byte-for-byte equal to reviewer-findings.diff; no refresh was needed.

Restore confirmation

The only cleanup command ran exactly as required and completed with exit code 0:

pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore
→ Message: No baseline state found
→ Restored: False

This is the skill-sanctioned completion for the verified no-state path: baseline establishment created no state and candidate 2 made no tracked edits. All pre-existing harness changes remain untouched.

Structured result

Field Value
approach Generic per-control capability interfaces with old aliased interfaces as closed compatibility specializations (designed, not applied)
files_changed none
result Blocked
analysis Baseline rejected the pre-existing dirty harness workspace and emitted no state/allow-list; the distinct design also entails an API explosion outside the bounded target set
diff empty
findings_count 0
status Done (final bounded candidate; deterministic Blocked, not NeedsRetry)

📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current description is strong but its test section uses the stale TestAssembly assembly name, omits the eight-test multi-TFM drift guard and the shared #37854 dependency, and does not state the control-specific mapper compatibility boundary.

Recommended title

[net11.0] Handlers: Add platform-neutral contracts for external backends

Recommended description

### Description of Change

Adds a small, additive set of platform-neutral handler contracts so that a platform backend shipping **outside** dotnet/maui can participate in .NET MAUI's strongly typed handler APIs using its own native view types.

#### The problem

Every per-control handler interface in `Microsoft.Maui.Core` declares `PlatformView` through a `using PlatformView = ...` alias that resolves to a different native type per target framework:

```csharp
#if __IOS__ || MACCATALYST
using PlatformView = Microsoft.Maui.Platform.MauiLabel;
#elif MONOANDROID
using PlatformView = AndroidX.AppCompat.Widget.AppCompatTextView;
#elif WINDOWS
using PlatformView = Microsoft.UI.Xaml.Controls.TextBlock;
#elif TIZEN
using PlatformView = Tizen.UIExtensions.NUI.Label;
#elif (NETSTANDARD || !PLATFORM) || ...
using PlatformView = System.Object;
#endif

public partial interface ILabelHandler : IViewHandler
{
    new ILabel VirtualView { get; }
    new PlatformView PlatformView { get; }
}
```

The alias is baked into the compiled contract, so the interface can only be implemented by a handler whose native type is *exactly* the type MAUI picked. An external backend owns its own native types, so it cannot implement those interfaces:

| TFM the backend consumes | Compiled `PlatformView` | Error |
| --- | --- | --- |
| A platform TFM MAUI ships | MAUI's own native type | `CS0738` |
| The neutral `net11.0` TFM | non-nullable `System.Object` | `CS9333`, plus `CS8766` when warnings are errors |

Reproduced against `Microsoft.Maui.Core 11.0.0-preview.7.26406.9` with a plain `net11.0` class library:

```csharp
public class MyNativeLabel { }

public class MyLabelHandler : ViewHandler<ILabel, MyNativeLabel>, ILabelHandler
{
    public MyLabelHandler() : base(LabelHandler.Mapper) { }
    protected override MyNativeLabel CreatePlatformView() => new();
    ILabel ILabelHandler.VirtualView => VirtualView;
    MyNativeLabel ILabelHandler.PlatformView => PlatformView; // CS9333
}
```

```text
error CS9333: 'MyLabelHandler.PlatformView': type must be 'object' to match implemented member 'ILabelHandler.PlatformView'
error CS8766: Nullability of reference types in return type of 'object? ViewHandler.PlatformView.get' doesn't match
              implicitly implemented member 'object ILabelHandler.PlatformView.get'
```

Core has 46 handler interfaces using this alias pattern. `ILabelHandler`, `IContentViewHandler`, `ILayoutHandler`, and `IWindowHandler` are the first contracts needed for an application → window → page → content → layout → label vertical slice. `ILayoutHandler` is the most consequential because it also carries `Add`, `Remove`, `Clear`, `Insert`, `Update`, and `UpdateZIndex` behavior.

#### The solution

Adds three interfaces. Nothing is moved, renamed, or removed:

```csharp
namespace Microsoft.Maui;

public interface IElementHandler<out TVirtualView, out TPlatformView> : IElementHandler
    where TVirtualView : IElement
    where TPlatformView : class
{
    new TVirtualView VirtualView { get; }
    new TPlatformView PlatformView { get; }
}

public interface IViewHandler<out TVirtualView, out TPlatformView>
    : IElementHandler<TVirtualView, TPlatformView>, IViewHandler
    where TVirtualView : IView
    where TPlatformView : class
{
    new TVirtualView VirtualView { get; }
}

public interface ILayoutHandler<out TPlatformView> : IViewHandler<ILayout, TPlatformView>
    where TPlatformView : class
{
    void Add(IView view);
    void Remove(IView view);
    void Clear();
    void Insert(int index, IView view);
    void Update(int index, IView view);
    void UpdateZIndex(IView view);
}
```

`ElementHandler<TVirtualView, TPlatformView>` and `ViewHandler<TVirtualView, TPlatformView>` implement their matching generic interfaces. Their existing public `VirtualView` and `PlatformView` properties already have the required signatures, so no derived handler needs another member. All 46 aliased in-box handlers and every third-party handler derived from these generic bases are automatically recognizable through the neutral contracts.

`TPlatformView` is covariant, making `object` the platform-neutral wildcard:

```csharp
if (label.Handler is IViewHandler<ILabel, object> labelHandler)
{
    ILabel virtualView = labelHandler.VirtualView;
    object nativeLabel = labelHandler.PlatformView;
}
```

`ILayoutHandler<TPlatformView>` is deliberately unrelated to the existing `ILayoutHandler` by inheritance. Relating them would force `ILayoutHandler` to hide inherited members and could break types using explicit interface implementations. The in-box `LayoutHandler` lists both contracts and satisfies both with its existing public methods.

#### Mapper compatibility

Property and command mapper infrastructure and key routing are unchanged. External handlers should own mappers typed to their handler classes and normally chain them from neutral base mappers such as `ElementHandler.ElementMapper`, `ViewHandler.ViewMapper`, or `ViewHandler.ViewCommandMapper`.

In-box control-specific mappers such as `WindowHandler.Mapper`, `LayoutHandler.Mapper`, and `LayoutHandler.CommandMapper` remain typed to their corresponding aliased handler interfaces. A handler implementing only a new generic neutral contract cannot reuse those mapper instances because mapper invocation casts to the aliased handler type. For layout behavior, external mappers should register the same `nameof(ILayoutHandler.Add)`/`Remove`/`Clear`/`Insert`/`Update`/`UpdateZIndex` command keys that Controls already raises.

#### Backward compatibility

- No member moved off `ILabelHandler`, `IContentViewHandler`, `ILayoutHandler`, or `IWindowHandler`.
- No existing aliased interface gained or lost a base interface.
- Handler registration and `ToHandler`/`ToPlatform` are unchanged.
- Existing casts such as `Handler as ILayoutHandler` in the obsolete Controls compatibility layer are unchanged and still return `null` for a handler implementing only `ILayoutHandler<TPlatformView>`.
- Existing property and command mapper types are unchanged.

Derived handlers and handlers implementing `ILabelHandler`/`ILayoutHandler` with explicit-only members were compiled against `Microsoft.Maui.Core 11.0.0-preview.7.26406.9` and loaded against a build containing this change. They type-load without `TypeLoadException`, and their existing `is`/cast relationships remain intact.

A pre-existing type that implements `ILayoutHandler` explicitly does not automatically become `ILayoutHandler<object>` because it never lists the generic interface. Nothing in MAUI is switched to check only the neutral form.

#### Follow-up coverage

The generic contracts cover every handler automatically for recognition and typed access. Remaining work is separate:

1. Other interfaces carrying behavior rather than accessors, such as `IScrollViewHandler`, can receive an `ILayoutHandler<TPlatformView>`-style neutral counterpart on demand.
2. Handler infrastructure that remains `internal` or TFM-locked includes the `ViewHandler.ContainerView` setter, `MauiContext.AddSpecific`, `LifecycleEventServiceExtensions.InvokeLifecycleEvents`, `Microsoft.Maui.Handlers.LayoutExtensions`, and `HandlerNotFoundException`.

### Issues Fixed

Unblocks external platform backends, such as a standalone Tizen backend, that were blocked on gap G2: handler interfaces binding `PlatformView` to a per-TFM alias.

### Tests

- Extends the external-backend test-support project shared with [#37854](https://github.com/dotnet/maui/pull/37854). `Microsoft.Maui.Core.ExternalBackend.TestSupport` is deliberately absent from Core's `InternalsVisibleTo` list and builds with `TreatWarningsAsErrors=true`.
- Makes that project mirror Core's `netstandard2.1;netstandard2.0;$(_MauiDotNetTfm);$(MauiPlatforms)` expression. Per-platform fake native views cover Android, iOS/Mac Catalyst, Windows, Tizen, and neutral TFMs while retaining the shared container-view sources on their supported TFMs.
- Adds 18 `ExternalPlatformBackendTests` covering external and in-box contract satisfaction, covariance, registration, neutral base-mapper composition, Controls layout command routing, and preservation of the aliased interfaces.
- Adds 8 `ExternalBackendTargetFrameworkTests` that compare the embedded Core and external-backend project TFM expressions and require fake-native-view sources for every platform.

Local validation reported:

| Suite | Result |
| --- | --- |
| `Core.UnitTests` | 966 passed, 3 skipped, 0 failed |
| `Controls.Core.UnitTests` | 6207 passed, 30 skipped, 0 failed |
| Core `net11.0` / `netstandard2.0` / `netstandard2.1` with `PublicApiType=Validate` | build succeeded |
| `dotnet format --verify-no-changes` on changed files | clean |

Platform TFMs (`-android`, `-ios`, `-maccatalyst`, `-windows`) remain covered by CI because the required workloads were not installed on the local validation machine.

### Docs

`docs/design/ExternalPlatformBackends.md` documents the alias problem, the new contracts, mapper-compatible adoption patterns, target-framework coverage, and remaining follow-up work.

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

The submitted API and implementation are technically sound, additive, and
well-covered by the retained Gate evidence, but two public documentation
statements give external backend authors unsafe mapper guidance. The
pr-plus-reviewer candidate keeps the submitted implementation unchanged and
corrects both issues in one focused patch.

Comparative Ranking

Rank Candidate Implementation quality Regression evidence Result
1 pr-plus-reviewer Preserves the sound covariant contracts and corrects the invalid window-mapper example plus the inaccurate layout-cast guidance. Its one fresh targeted run was blocked, not failed, by a missing sandbox project.assets.json. The functional implementation is identical to pr, whose retained with-fix evidence passed all 18 primary and 8 TFM-regression tests. Winner
2 pr The runtime/API design is sound, but IElementHandlerOfT.cs recommends WindowHandler.Mapper to a handler that cannot satisfy its IWindowHandler cast, and ILayoutHandlerOfT.cs incorrectly calls one compatibility cast the sole remaining runtime cast. Passed: 18/18 ExternalPlatformBackendTests and 8/8 ExternalBackendTargetFrameworkTests in the retained with-fix Gate runs. The Gate remains inconclusive only because its reconstructed without-fix baseline cannot compile tests that reference newly added production types. Viable after documentation corrections
3 try-fix-1 Proposed default-interface-member bridges move type validation from compile time to runtime casts and provide no implemented patch to evaluate. Blocked: no files changed and no tests ran because baseline establishment produced no edit allow-list. Unproven and riskier
4 try-fix-2 Proposed generic per-control interfaces would multiply API surface across aliased handler families and was acknowledged as materially less viable than the cross-cutting PR design. Blocked: no files changed and no tests ran because baseline establishment produced no edit allow-list. Incomplete and unproven

No candidate recorded a regression-test failure. The two try-fix designs are
ranked below the implemented candidates because they produced neither a diff nor
validation evidence. The pr-plus-reviewer validation block is retained as
uncertainty rather than treated as a failure: the only delta from the tested raw
PR is XML documentation, and git diff --check passed.

Expert Review Reconciliation

The expert review found no defect in covariance, nullability, handler
conformance, Android constraints, PublicAPI synchronization, or backward
compatibility. Its two actionable findings are both resolved by the winning
candidate:

  1. External handlers now use backend-owned mappers chained from neutral base
    mappers rather than an in-box mapper typed to an aliased interface.
  2. Layout documentation now distinguishes type-agnostic command keys from
    mapper instances that cast to ILayoutHandler, and no longer overstates the
    obsolete compatibility-property cast.

Because the winning corrections are not in the submitted PR HEAD, the submitted
PR should be updated before approval.


📱 UI Tests — ViewBaseTests

Detected UI test categories: ViewBaseTests

✅ Deep UI tests — 118 passed, 0 failed, 1 skipped across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
ViewBaseTests 118/119 (1 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The submitted covariant handler contracts are the strongest implemented design, and the pr-plus-reviewer candidate preserves them while correcting two public documentation hazards around aliased mapper casts. Its focused validation was blocked by missing sandbox restore assets rather than a test failure; the identical functional implementation passed the retained 18 primary and 8 target-framework regression tests.

Address the actionable findings in this review before merging.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 28, 2026
Copilot AI review requested due to automatic review settings August 28, 2026 18:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 29 out of 29 changed files in this pull request and generated 3 comments.

Comment on lines +62 to +64
public interface IElementHandler<out TVirtualView, out TPlatformView> : IElementHandler
where TVirtualView : IElement
where TPlatformView : class
Comment on lines +45 to +47
public interface IViewHandler<out TVirtualView, out TPlatformView> : IElementHandler<TVirtualView, TPlatformView>, IViewHandler
where TVirtualView : IView
where TPlatformView : class
Comment on lines +75 to +79
public static void MapContent(FakeContentViewHandler handler, IContentView contentView)
{
handler.PlatformView.FakeContent =
(contentView.PresentedContent as IView)?.Handler?.PlatformView as FakeNativeView;
}
@kubaflo

kubaflo commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@kubaflo
kubaflo merged commit 07bfb31 into net11.0 Aug 29, 2026
138 of 147 checks passed
@kubaflo
kubaflo deleted the redth-external-handler-interface-contracts branch August 29, 2026 21:59
@github-actions github-actions Bot added this to the .NET 11.0-preview7 milestone Aug 29, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-core-platform Integration with platforms s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants